package com.kim.smartring.broadcastreceiver;

import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.kim.smartring.activity.SmartRingMainActivity;
import com.kim.smartring.ble.BleWrapper;
import com.kim.smartring.ble.BleWrapperUiCallbacks;
import com.kim.smartring.utils.BLEDataUtils;
import com.kim.smartring.utils.ConfigUtils;

public class BLEBroadcastReceiver extends BroadcastReceiver {

	private static final String TAG = "BLEBroadcastReceiver";

	public static final String FLAG_SERVICE_UUID = "suuid";
	public static final String FLAG_CHARACTERISTIC_UUID = "cuuid";
	public static final String FLAG_DATA = "data";
	public static final String FLAG_NOTIFY = "notify";

	public static final String BS_ACTION_INIT = "com.kim.smartring.init";
	public static final String BS_ACTION_CONNECT = "com.kim.smartring.connection"; // 连接当前已绑定设备
	public static final String BS_ACTION_RELEASE_CONNECTION = "com.kim.smartring.release.connection";
	public static final String BS_ACTION_GET_CACHED_SERVICES = "com.kim.smartring.cached_service";
	public static final String BS_ACTION_SMARTRING_ALERT = "com.kim.smartring.sr_alert"; // 手环报警
	public static final String BS_ACTION_PHONE_ALERT = "com.kim.smartring.p_alert";
	public static final String BS_ACTION_WIRTE_ALARM = "com.kim.smartring.wa"; // 设置闹钟
	public static final String BS_ACTION_WRITE_DATA = "com.kim.smartring.write_data"; // 向智能手环写数据
	public static final String BS_ACTION_NOTIFY = "com.kim.smartring.notify"; // 设置notify

	private Handler mHandler;
	private BleWrapper mBleWrapper;

	/**
	 * 连接到蓝牙
	 * 
	 * @param activity
	 * @param action
	 */
	public static void connect2Ble(Activity activity, String action) {
		Intent intent = new Intent();
		intent.setAction(action);
		activity.sendBroadcast(intent);
	}

	/**
	 * 释放蓝牙连接
	 * 
	 * @param activity
	 * @param action
	 */
	public static void releaseConnection(Activity activity, String action) {
		Intent intent = new Intent();
		intent.setAction(action);
		activity.sendBroadcast(intent);
	}

	/**
	 * 获取蓝牙设备服务
	 * 
	 * @param activity
	 * @param action
	 */
	public static void getCachedServices(Activity activity, String action) {
		Intent intent = new Intent();
		intent.setAction(action);
		activity.sendBroadcast(intent);
	}

	/**
	 * 向蓝牙设备写数据
	 * 
	 * @param activity
	 * @param action
	 * @param data
	 * @param serviceUUID
	 * @param characteristicUUID
	 */
	public static void writeDataToSmartRing(Activity activity, String data,
			String serviceUUID, String characteristicUUID) {
		Intent intent = new Intent();
		intent.setAction(BS_ACTION_WRITE_DATA);
		intent.putExtra(BLEBroadcastReceiver.FLAG_SERVICE_UUID, serviceUUID);
		intent.putExtra(BLEBroadcastReceiver.FLAG_CHARACTERISTIC_UUID,
				characteristicUUID);
		intent.putExtra(BLEBroadcastReceiver.FLAG_DATA, data);
		activity.sendBroadcast(intent);
	}

	public static void enableNotify(Activity activity, String serviceUUID,
			String characteristicUUID, boolean isEnable) {
		Intent intent = new Intent();
		intent.setAction(BS_ACTION_NOTIFY);
		intent.putExtra(BLEBroadcastReceiver.FLAG_SERVICE_UUID, serviceUUID);
		intent.putExtra(BLEBroadcastReceiver.FLAG_CHARACTERISTIC_UUID,
				characteristicUUID);
		intent.putExtra(BLEBroadcastReceiver.FLAG_NOTIFY, isEnable);
		activity.sendBroadcast(intent);
	}

	/**
	 * 
	 * @param parent
	 * @param callback
	 * @param handler
	 */
	public BLEBroadcastReceiver(Activity parent,
			BleWrapperUiCallbacks callback, Handler handler) {
		this.mHandler = handler;
		mBleWrapper = new BleWrapper(parent, callback);
		if (!mBleWrapper.initialize()) {
			// 初始化蓝牙失败
			Log.d(TAG, "Ble init failed...");
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (BS_ACTION_CONNECT.equals(action)) {
			connectBle();
		} else if (BS_ACTION_RELEASE_CONNECTION.equals(action)) {
			releaseConnection();
		} else if (BS_ACTION_GET_CACHED_SERVICES.equals(action)) {
			printAvailableServices();
		} else if (BS_ACTION_SMARTRING_ALERT.equals(action)) {
			smartringLosslinkAlert();
		} else if (BS_ACTION_PHONE_ALERT.equals(action)) {
			phoneAlert();
		} else if (BS_ACTION_WRITE_DATA.equals(action)) { // 向智能手环设备写数据
			String data = intent.getStringExtra(FLAG_DATA);
			String serviceUUID = intent.getStringExtra(FLAG_SERVICE_UUID);
			String characteristicUUID = intent
					.getStringExtra(FLAG_CHARACTERISTIC_UUID);
			writeData2SmartRing(data, serviceUUID, characteristicUUID);
		} else if (BS_ACTION_NOTIFY.equals(action)) { // 设置notify
			boolean enable = intent.getBooleanExtra(FLAG_NOTIFY, false);
			String serviceUUID = intent.getStringExtra(FLAG_SERVICE_UUID);
			String characteristicUUID = intent
					.getStringExtra(FLAG_CHARACTERISTIC_UUID);
			enableNotify(serviceUUID, characteristicUUID, enable);
		}
	}

	private boolean bleBasicFunctionAvailable() {
		if (!mBleWrapper.isBtEnabled()) { // 蓝牙未使能
			mHandler.sendEmptyMessage(SmartRingMainActivity.MSG_BLE_NOT_ENABLE);
			return false;
		}
		if (!ConfigUtils.isDeviceBinded()) { // 设备未绑定
			mHandler.sendEmptyMessage(SmartRingMainActivity.MSG_BLE_NOT_BINDING);
			return false;
		}
		return true;
	}

	private boolean isConnected() {
		return mBleWrapper.isConnected();
	}

	private void connectBle() {
		if (!bleBasicFunctionAvailable()) {
			return;
		}
		String deviceName = ConfigUtils.getBindedDeviceName();
		String deviceAddress = ConfigUtils.getBindedDeviceAddress(deviceName);
		mBleWrapper.connect(deviceAddress);
	}

	private void releaseConnection() {
		mBleWrapper.stopMonitoringRssiValue();
		mBleWrapper.diconnect();
		mBleWrapper.close();
	}

	private void smartringLosslinkAlert() {
		if (!bleBasicFunctionAvailable()) {
			return;
		}
		if (!mBleWrapper.isConnected()) { // 设备已断开连接 尝试重新连接
			connectBle();
		}

		List<BluetoothGattService> bluetoothGattServices = mBleWrapper
				.getCachedServices();
		// 找到对应的服务和特性
		// 写入手环警告标识

		// TODO
	}

	private void phoneAlert() {
		if (!bleBasicFunctionAvailable()) {
			return;
		}
		if (!mBleWrapper.isConnected()) { // 设备已断开连接 尝试重新连接
			connectBle();
		}

		List<BluetoothGattService> bluetoothGattServices = mBleWrapper
				.getCachedServices();
		// 找到对应的服务和特性
		// 写入手环警告标识

		// TODO
	}

	private void printAvailableServices() {
		Log.d(TAG, "print available service----------->");
		for (BluetoothGattService service : mBleWrapper.getCachedServices()) {
			Log.d(TAG, String.format("available service name:%s", service
					.getUuid().toString()));

		}
	}

	/**
	 * 写数据到手环
	 * 
	 * @param data
	 * @param serviceUUID
	 * @param characteristicUUID
	 */
	private void writeData2SmartRing(String data, String serviceUUID,
			String characteristicUUID) {
		if (!bleBasicFunctionAvailable()) {
			return;
		}
		if (!isConnected()) {
			connectBle();
			mHandler.sendEmptyMessage(SmartRingMainActivity.MSG_BLE_NOT_CONNECTED);
			return;
		}
		BLEDataUtils.writeDataToSmartRing(mBleWrapper, data, serviceUUID,
				characteristicUUID);
	}

	private void enableNotify(String serviceUUID, String characteristicUUID,
			boolean enable) {
		if (!bleBasicFunctionAvailable()) {
			return;
		}
		if (!isConnected()) {
			connectBle();
			mHandler.sendEmptyMessage(SmartRingMainActivity.MSG_BLE_NOT_CONNECTED);
			return;
		}
		BLEDataUtils.enableNofity(mBleWrapper, serviceUUID, characteristicUUID,
				enable);
	}
}
